import { config } from "@/config"; //系统配置
import EsriConfig from "@arcgis/core/config"; //Esri配置
import Map from "@arcgis/core/Map"; //地图
import MapView from "@arcgis/core/views/MapView"; //视图
import BasemapToggle from "@arcgis/core/widgets/BasemapToggle"; //底图切换
import TileLayer from "@arcgis/core/layers/TileLayer"; //瓦片图层
import MapImageLayer from "@arcgis/core/layers/MapImageLayer"; //动态图层
import FeatureLayer from "@arcgis/core/layers/FeatureLayer"; //要素图层
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer"; //要素集
import Swipe from "@arcgis/core/widgets/Swipe"; //卷帘
import UniqueValueRenderer from "@arcgis/core/renderers/UniqueValueRenderer"; //唯一值渲染
import Expand from "@arcgis/core/widgets/Expand"; //收缩展开组件
import ScaleBar from "@arcgis/core/widgets/ScaleBar"; //比例尺组件
import FullscreenViewModel from "@arcgis/core/widgets/Fullscreen/FullscreenViewModel"; //全屏组件
// 工具
import Draw from "@arcgis/core/views/draw/Draw";
import Graphic from "@arcgis/core/Graphic";
import Point from "@arcgis/core/geometry/Point";
import Polyline from "@arcgis/core/geometry/Polyline";
import Polygon from "@arcgis/core/geometry/Polygon";

//样式
import SimpleMarkerSymbol from "@arcgis/core/symbols/SimpleMarkerSymbol";
import SimpleLineSymbol from "@arcgis/core/symbols/SimpleLineSymbol";
import SimpleFillSymbol from "@arcgis/core/symbols/SimpleFillSymbol";
import TextSymbol from "@arcgis/core/symbols/TextSymbol";
//查询
import Query from "@arcgis/core/tasks/support/Query";
import IdentifyParameters from "@arcgis/core/tasks/support/IdentifyParameters";
import IdentifyTask from "@arcgis/core/tasks/IdentifyTask";
//图形工具
import {
  intersect,
  disjoint,
  geodesicArea, //地理坐标计算
  geodesicLength,
  planarLength, //投影坐标计算
  planarArea,
} from "@arcgis/core/geometry/geometryEngine";

import { initWidget } from "./config";
import mapAxios from "axios";
import {
  AddCollection,
  DeleteCollection,
  GetCollectionByUserId,
} from "@/api/map/collect";
import { ElMessage } from "element-plus";
import store from "@/store";
import { nextTick, ref } from "vue";
import { getCollectionList } from "./collection";
import Extent from "@arcgis/core/geometry/Extent";

let map: Map;
let mapView: MapView;
let draw: Draw;
let expand: Expand;
let mapClickHandle: any;

const locateLayer = new GraphicsLayer({ id: "locateLayerId" }); //定位图层
const lineLayer = new GraphicsLayer(); //绘制线图层
const polygonLayer = new GraphicsLayer(); //绘制面图层
// 图例
let legendList: any = ref([]);
// 要素图层集合、属性查询
let FeatureLayerList: any = [];
// 所有地图集合
let operateFeatureLayerList: any = [];

// 卷帘
let rollerView: any = null;
let dialogRollerVisible = ref(false);
let leftSelectedLayer = ref(config.rollerLeftLayer.name);
let rightSelectedLayer = ref(config.rollerRightLayer.name);
let allLayerList: any = ref([]);
let swipe: Swipe;

// screen中的视图集合
let screenViewList: any = [];
let screenMapList: any = [];

//分屏中使用的参数
// 是否显示分屏
let dialogNormalVisible = ref(false);
// 双屏或四屏
let screenNum: any = ref(2);
let cloNum: any = ref(12);
let screenClass: any = ref(
  "padding-bottom: 86%; position: relative; margin: 0px auto;"
);

let classType2: any = ref("primary");
let classType4: any = ref("");
// 选中的图层
let screenSelectedLayer1 = ref(config.rollerLeftLayer.name);
let screenSelectedLayer2 = ref(config.rollerRightLayer.name);
let screenSelectedLayer3 = ref(config.rollerRightLayer.name);
let screenSelectedLayer4 = ref(config.rollerLeftLayer.name);

let mapFullscreenBtn: any = null;

let dialogResultVisible = ref(false);

const initMap = (viewId: any) => {
  EsriConfig.assetsPath = config.map_preview_config.assetsPath;
  EsriConfig.fontsUrl = config.map_preview_config.fontsUrl;
  map = new Map();
  mapView = new MapView({
    popup: {
      autoOpenEnabled: false,
    },
    container: viewId,
    map: map,   
  });
  
  
  // 移除放大缩小组件以及Esri Logo标志
  mapView.ui.remove(["attribution", "zoom"]);
  // 设置底图相关操作
  map.basemap = initWidget().baseMap_img;
  // map.basemap = initWidget().baseMap_vec;
  // 添加底图切换的操作
  const basemapToggle = new BasemapToggle({
    view: mapView,
    nextBasemap: initWidget().baseMap_vec,
  });

  // 比例尺设定
  let scaleBar = new ScaleBar({
    view: mapView,
    id: "scaleBarId",
    style: "ruler",
    unit: "metric",
    visible: true,
  });
  //收缩展开，用于控制图例显示
  expand = new Expand({
    content: document.getElementById("infoDiv") as HTMLDivElement,
    view: mapView,
    expanded: false,
  });
  mapView.ui.add([expand, basemapToggle, scaleBar], "bottom-right");

  //全屏功能
  mapFullscreenBtn = new FullscreenViewModel({
    view: mapView,
    // element: document.getElementById("fullscreen") as HTMLLIElement,
  });

  mapView.extent = new Extent({
    xmin: 2.8811562296240337E7,
    ymin: 4203101.38674231,
    xmax: 3.0398047768926658E7,
    ymax: 4940798.408266791,
    spatialReference:
    {
      wkid: 4517
    }
  });
  //视图加载完成
  mapView.when(function () {
    map.layers.add(locateLayer);
    draw = new Draw({
      view: mapView,
    });
  });
};
const operateFeatureLayer = (operateFeatureLayer: any) => {
  switch (operateFeatureLayer.type) {
    case "addOrRemoveLayer": //标准目录，专题目录，已选图层中的图层操作（打开或关闭）
      if (map.layers.find((layer: any) => layer.id == operateFeatureLayer.id)) {
        let _operateLayer = map.layers.find(
          (layer: any) => layer.id == operateFeatureLayer.id
        );
        _operateLayer.visible = operateFeatureLayer.open;
        // operateFeatureLayerList.splice(_operateLayer, 1);
        if (operateFeatureLayer.open) {
          //添加图例
          mapAxios
            .get(operateFeatureLayer.serviceUrl + "/legend?f=pjson")
            .then((res: any) => {
              if (!!res.data) {
                legendList.value.push({
                  id: operateFeatureLayer.id,
                  name: operateFeatureLayer.name,
                  legends: res.data.layers,
                });
              }
            })
            .catch((err) => {
              console.log("err: ", err);
            });
        } else {
          //从图例中移除
          let _legendIndex = legendList.value.findIndex(
            (item: any) => item.id == operateFeatureLayer.id
          );
          legendList.value.splice(_legendIndex, 1);
        }
      } else {
        // operateFeatureLayerList.push(operateFeatureLayer);
        if (operateFeatureLayer.serviceType == "0") {
          const transportationLayer = new TileLayer({
            id: operateFeatureLayer.id,
            url: operateFeatureLayer.serviceUrl,
            legendEnabled: false,
            visible: true,
          });
          map.add(transportationLayer);
        }
        if (operateFeatureLayer.serviceType == "1") {
          const mapImageLayer = new MapImageLayer({
            id: operateFeatureLayer.id,
            url: operateFeatureLayer.serviceUrl,
            legendEnabled: false,
            visible: true,
          });

          map.add(mapImageLayer);
        }
        //添加图例
        mapAxios
          .get(operateFeatureLayer.serviceUrl + "/legend?f=pjson")
          .then((res: any) => {
            if (!!res.data) {
              legendList.value.push({
                id: operateFeatureLayer.id,
                name: operateFeatureLayer.name,
                legends: res.data.layers,
              });
            }
          })
          .catch((err) => {
            console.log("err: ", err);
          });
      }
      break;
    case "opacityChange":
      if (map.layers.find((layer: any) => layer.id == operateFeatureLayer.id)) {
        map.layers.find(
          (layer: any) => layer.id == operateFeatureLayer.id
        ).opacity = operateFeatureLayer.opacity;
      }
      break;
    case "legendLayerAdd": //显示图例
      expand.toggle();
      break;
    case "fullAllLayer": //目录中的全图操作
      if (map.layers.find((layer: any) => layer.id == operateFeatureLayer.id)) {
        // mapView.center = [86.6, 40.7];
        let extent = map.layers.find(
          (layer: any) => layer.id == operateFeatureLayer.id
        ).fullExtent;
        mapView.goTo({ target: extent }, { duration: 2000 });
      }
      break;
    case "collectionLayer": //收藏功能
      // 获取收藏列表
      if (operateFeatureLayer.opt == "add") {
        AddCollection(operateFeatureLayer.userId, operateFeatureLayer.id)
          .then((res: any) => {
            ElMessage({ message: res.data.message, type: res.data.state });
            getCollectionList(operateFeatureLayer.userId);
          })
          .catch((err: any) => {
            console.log(err);
          });
      } else if (operateFeatureLayer.opt == "delete") {
        DeleteCollection(operateFeatureLayer.id)
          .then((res: any) => {
            ElMessage({ message: res.data.message, type: res.data.state });
            getCollectionList(operateFeatureLayer.userId);
          })
          .catch((err: any) => {
            console.log(err);
          });
      }

      break;
    case "locationHandle":
      // mapView.center = [operateFeatureLayer.lat, operateFeatureLayer.lng];
      locateByAreaCode(operateFeatureLayer.areaCode);
      break;
    case "mapFullView": //全图功能
      if (map.basemap && map.basemap.baseLayers.getItemAt(0)) {
        const extent = map.basemap.baseLayers.getItemAt(0).fullExtent;
        // mapView.extent = extent;
        mapView.goTo(
          {
            target: extent,
          },
          { duration: 2000 }
        );
      }
      break;
    case "attributeQuery": //属性查询
      if (
        operateFeatureLayer.layerList &&
        operateFeatureLayer.layerList.length > 0
      ) {
        (document.getElementById("viewDiv") as HTMLDivElement).style.cursor =
          "crosshair";
        // Identify方式
        mapClickHandle = mapView.on("click", (event: any) => {
          executeIdentifyTask(event, operateFeatureLayer.layerList);
        });
      } else {
        //没有选中图层
        ElMessage({
          message: "没有可查询的图层，请先选择图层。",
          type: "warning",
        });
      }
      break;
    case "screenView": //对比
      if (operateFeatureLayer.command == "normal") {
        dialogNormalVisible.value = true;
      }
      if (operateFeatureLayer.command == "roller") {
        dialogRollerVisible.value = true;
      }
      break;
    case "mapFullScreen": //全屏功能
      mapFullscreenBtn.toggle();
      break;
    case "mapClear": //清除功能
      //清除定位的图形
      locateLayer.removeAll();
      //清除测距测面的图形
      lineLayer.removeAll();
      polygonLayer.removeAll();
      draw.reset();

      mapView.graphics.removeAll();
      (document.getElementById("viewDiv") as HTMLDivElement).style.cursor =
        "default";
      if (mapClickHandle != null) mapClickHandle.remove();
      break;
    case "measure": //测距测面
      addGraphic(operateFeatureLayer.name);
      break;
  }
};
const executeIdentifyTask = (event: any, layerList: any) => {
  // console.log(store.getters["layers/getLayerList"]);
  store.dispatch("layers/INIT_RESULT", []);
  layerList.forEach((_layer: any) => {
    let pointSymbol: any = {
      type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
      color: "red",
      size: "20px", // pixels
      outline: {
        // autocasts as new SimpleLineSymbol()
        color: [128, 128, 128, 0.5],
        width: 5, // points
      },
    };
    mapView.graphics.removeAll();
    let graphic = new Graphic(event.mapPoint);
    graphic.symbol = pointSymbol;
    mapView.graphics.add(graphic);
    mapView.goTo({ target: graphic, zoom: 10 }, { duration: 2000 });

    let identifyTask = new IdentifyTask(_layer.serviceUrl);
    let params = new IdentifyParameters();
    params.tolerance = 0.1;
    params.layerOption = "visible";
    params.width = mapView.width;
    params.height = mapView.height;
    params.layerIds = [];
    params.geometry = event.mapPoint;
    params.mapExtent = mapView.extent;
    (document.getElementById("viewDiv") as HTMLDivElement).style.cursor =
      "wait";
    identifyTask.execute(params).then(function (response) {
      let results = response.results;
      let res: any = {
        layerName: _layer.name,
        results: results.map((item: any) => item.feature.attributes),
      };
      console.log("需要使用的结果：", res);
      store.dispatch("layers/ADD_RESULT", res);
    });
    identifyTask.destroy();
  });

  (document.getElementById("viewDiv") as HTMLDivElement).style.cursor =
    "crosshair";
  dialogResultVisible.value = true;
};

//卷帘分析
const rollerInit = (leftLayer: any, rightLayer: any) => {
  nextTick(() => {
    const rollerMap = new Map();
    const rollerLeftLayer = toEsriLayer(leftLayer);
    const rollerRightLayer = toEsriLayer(rightLayer);
    rollerMap.addMany([rollerRightLayer, rollerLeftLayer]);

    rollerView = new MapView({
      container: "screenRoller",
      map: rollerMap,
    });
    rollerView.ui.remove(["attribution", "zoom"]);
    // create a new Swipe widget
    swipe = new Swipe({
      leadingLayers: [rollerLeftLayer],
      trailingLayers: [rollerRightLayer],
      position: 50,
      view: rollerView,
    });

    // add the widget to the view
    rollerView.ui.add(swipe);
  });
};
const leftChanged = (val: string) => {
  rollerView.map.removeMany(swipe.leadingLayers);
  swipe.leadingLayers.removeAll();
  let leftLayer = allLayerList.value.find((item: any) => item.name == val);
  const rollerLeftLayer = toEsriLayer(leftLayer);
  rollerView.map.add(rollerLeftLayer);
  swipe.leadingLayers.add(rollerLeftLayer);
};
const rightChanged = (val: string) => {
  rollerView.map.removeMany(swipe.trailingLayers);
  swipe.trailingLayers.removeAll();
  let rightLayer = allLayerList.value.find((item: any) => item.name == val);
  const rollerRightLayer = toEsriLayer(rightLayer);
  rollerView.map.add(rollerRightLayer);
  swipe.trailingLayers.add(rollerRightLayer);
};

//多窗口对比分析
const selectType = (type: string, num: number, clo: number) => {
  screenViewList.value = [];
  screenNum.value = num;
  cloNum.value = clo;
  if (type === "classType2") {
    classType2.value = "primary";
    classType4.value = "";
    screenClass.value =
      "padding-bottom:86%; position: relative; margin: 0px auto;";
  } else if (type === "classType4") {
    classType2.value = "";
    classType4.value = "primary";
    screenClass.value =
      "padding-bottom: 43%; position: relative; margin: 0px auto;";
  }
  nextTick(() => {
    for (let i = 1; i < num + 1; i++) {
      screenMapList.push(new Map());
      // let screenMap = new Map();
      // let screenMap = new Map({ basemap: initWidget().baseMap_img });
      // 添加地图到分屏中
      let screenView = new MapView({
        container: "screen" + i,
        map: screenMapList[i - 1],
        // center: [-74, 40.73],
        // zoom: 10,
      });
      //eval("screenSelectedLayer"+i).value
      let _layerName = eval("screenSelectedLayer" + i).value;
      let _layer = allLayerList.value.find(
        (item: any) => item.name == _layerName
      );
      screenMapList[i - 1].add(toEsriLayer(_layer));
      screenView.ui.remove(["attribution", "zoom"]);
      screenViewList.push(screenView);
    }
    screenViewList.forEach(function (screenView: any) {
      //定义一个范围变量
      var fullextent: any = null;
      //设置鼠标滚轮事件
      screenView.on("mouse-wheel", function (e: any) {
        //延迟获取范围的函数
        window.setTimeout(function () {
          //获取操作图层的范围
          fullextent = screenView.extent;
          //遍历所有视图来设置这个范围
          screenViewList.forEach(function (nview: any) {
            nview.extent = fullextent;
          });
        }, 1000);
      });
      //设置鼠标拖拽事件
      screenView.on("drag", function (e) {
        //获取操作图层的范围
        fullextent = screenView.extent;
        //遍历所有视图来设置这个范围
        screenViewList.forEach(function (nview: any) {
          nview.extent = fullextent;
        });
      });
    });
  });
};
const screenChange = (val: string, index: number) => {
  let _layer = allLayerList.value.find((item: any) => item.name == val);
  if (screenViewList[index - 1] && screenMapList[index - 1] && _layer) {
    // 移除地图
    screenMapList[index - 1].removeAll();
    screenMapList[index - 1].add(toEsriLayer(_layer));
  }
};
const getGraphics = (response: any, featureLayerList: any) => {
  (document.getElementById("viewDiv") as HTMLDivElement).style.cursor =
    "crosshair";

  if (response.results.length > 0) {
    response.results.forEach((res: any, i: number) => {
      FeatureLayerList.forEach((item: any, index: number) => {
        const graphic = res.graphic;
        if (graphic.layer.id == item.id && item.id != "0") {
          var attributes = graphic.attributes;
          var name = attributes.Section;
          var wind = attributes.Section_Num;

          console.log(name);

          // dom.byId("info").style.visibility = "visible";
          // dom.byId("name").innerHTML = name;
          // dom.byId("category").innerHTML = "Category " + category;
          // dom.byId("wind").innerHTML = wind + " kts";

          // symbolize all line segments with the given
          // storm name with the same symbol

          var renderer = new UniqueValueRenderer({
            type: "unique-value",
            field: "REGION",
            uniqueValueInfos: [
              {
                value: name,
                symbol: {
                  type: "simple-fill", // autocasts as new SimpleFillSymbol()
                  color: "red",
                },
              },
            ],
          });
          item.renderer = renderer;
        }
      });
    });
  }
};
const locateByAreaCode = (code: number) => {
  locateLayer.removeAll();
  let _locateLayer: any = map.findLayerById("locateLayerId");
  console.log(code);
  if (_locateLayer && _locateLayer.url != null) {
  } else {
    _locateLayer = new FeatureLayer({
      url: config.locateUrl,
      outFields: ["xzqdm", "xzqmc"],
      id: "locateLayerId",
      // visible: false,
    });
    // map.layers.add(_locateLayer);
  }
  const query = new Query();
  query.where = "xzqdm like'%" + code + "%' ";
  query.outSpatialReference = mapView.spatialReference;
  query.returnGeometry = true;
  query.outFields = ["*"];
  _locateLayer.queryFeatures(query).then(function (results: any) {
    console.log(results.features); // prints the array of features to the console

    let fillResultSymbol = new SimpleFillSymbol({
      color: [1, 234, 254, 0],
      style: "solid",
      outline: {
        width: 2,
        color: [1, 234, 254],
      },
    });
    // 不能加数字定位标记，图形数量和查询数量不对等，原因是由于一个小区园区编号可对应多个案卷号
    results.features.forEach((element: any, index: number) => {
      // 添加定位的点标记
      var graphic = new Graphic({
        geometry: element.geometry,
        symbol: fillResultSymbol,
        attributes: element.attributes,
      });

      locateLayer.add(graphic);
    });
    mapView.goTo(
      {
        target: locateLayer.graphics,
      },
      { duration: 2000 }
    );
  });
};
// ToEsriLayer
const toEsriLayer = (layer: any) => {
  const _layer =
    layer.serviceType == 0
      ? new TileLayer({
        url: layer.serviceUrl,
        id: layer.id,
        legendEnabled: false,
        visible: true,
      })
      : new MapImageLayer({
        url: layer.serviceUrl,
        id: layer.id,
        legendEnabled: false,
        visible: true,
      });
  return _layer;
};
// 绘制添加图形
const addGraphic = (drawAction: any) => {
  //清除之前绘制
  mapView.graphics.removeAll();

  const actionType =
    drawAction == "query_polygon" || drawAction == "measureArea"
      ? "polygon"
      : drawAction == "measureDistance"
        ? "polyline"
        : drawAction;
  const action = draw.create(actionType, {
    mode: "click",
    // mode: "hybrid"
  });
  mapView.focus();

  debugger
  switch (drawAction) {
    case "measureDistance":
      action.on(
        [
          "vertex-add",
          "vertex-remove",
          "cursor-update",
          // "redo",
          // "undo",
          "draw-complete",
        ],
        measureDistance
      );
      break;
    case "measureArea":
      action.on(
        [
          "vertex-add",
          "vertex-remove",
          "cursor-update",
          // "redo",
          // "undo",
          "draw-complete",
        ],
        measureArea
      );
      break;
  }
};

/**
 * 测距，测面
 */
function measureDistance(event: any) {
  if (event.vertices.length > 0) {
    lineLayer.removeAll(); //清空上次绘制的线
    let symbol = new SimpleMarkerSymbol({
      color: [1, 234, 254],
      size: 10,
      style: "circle",
      outline: {
        width: 1,
        color: [255, 255, 255],
      },
    });
    //将起点添加到地图
    let startGraphics = new Graphic({
      geometry: new Point({
        x: event.vertices[0][0], //当底图是投影坐标系时用x,地理坐标系用longitude
        y: event.vertices[0][1], //当底图是投影坐标系时用y,地理坐标系用latitude
        spatialReference: mapView.spatialReference, //和底图相同的坐标系
      }),
      symbol: symbol,
    });

    lineLayer.add(startGraphics);
    //将线添加到地图
    let lineSymbol = new SimpleLineSymbol({
      width: 2,
      color: "#01EAFE",
      style: "dash",
      cap: "round",
      join: "round",
    });
    let lineGraphics = new Graphic({
      geometry: new Polyline({
        paths: event.vertices,
        spatialReference: mapView.spatialReference,
      }),
      symbol: lineSymbol,
    });
    lineLayer.add(lineGraphics);

    //测距
    let linePath = <any>[]; //线段坐标集合
    let pointStart = <any>[]; //起点
    pointStart.push(event.vertices[0][0]);
    pointStart.push(event.vertices[0][1]);
    linePath.push(pointStart);

    for (let i = 1; i < event.vertices.length; i++) {
      //获得鼠标移动的坐标信息
      let point = new Point({
        x: event.vertices[i][0],
        y: event.vertices[i][1],
        spatialReference: mapView.spatialReference,
      });
      //鼠标位置
      let mouseGraphics = new Graphic({
        geometry: point,
        symbol: symbol,
      });
      let xy = <any>[]; //鼠标当前经纬度
      xy.push(event.vertices[i][0]);
      xy.push(event.vertices[i][1]);
      linePath.push(xy);
      let line = new Polyline({
        //起点到当前鼠标的线段
        paths: linePath,
        spatialReference: mapView.spatialReference,
      });
      // let length = geodesicLength(line, "meters"); //测距
      let length = planarLength(line, "meters"); //测距
      let lengthText = lengthFormat(length); //单位转换
      let textSymbol = new TextSymbol({
        color: "white",
        haloColor: "black",
        haloSize: "2px",
        text: lengthText,
        xoffset: "50px",
        yoffset: "-5px",
        font: {
          size: "16px",
          family: "sans-serif",
          weight: "bold",
        },
      });
      let textGraphics = new Graphic({
        //标注位置为鼠标位置
        geometry: point,
        symbol: textSymbol,
      });
      //将标注和鼠标位置添加到地图
      lineLayer.addMany([textGraphics, mouseGraphics]);
    }
    map.add(lineLayer);
  }
}

function measureArea(event: any) {
  if (event.vertices.length > 0) {
    polygonLayer.removeAll();
    let symbol = new SimpleMarkerSymbol({
      color: [255, 255, 255],
      size: 10,
      outline: {
        color: [0, 0, 0],
        width: 1,
      },
    });
    let fillSymbol = new SimpleFillSymbol({
      color: [3, 255, 240, 0.1],
      style: "solid",
      outline: {
        width: 2,
        color: [255, 116, 3],
      },
    });
    let polygon = new Polygon({
      rings: event.vertices,
      spatialReference: mapView.spatialReference,
    });

    let polygonGraphics = new Graphic({
      geometry: polygon,
      symbol: fillSymbol,
    });
    polygonLayer.add(polygonGraphics);
    // let area = geodesicArea(polygon, "square-meters");
    let area = planarArea(polygon, "square-meters");
    let areaText = areaFormat(Math.abs(area));
    let center = polygon.centroid;
    let pointCenter = new Point({
      longitude: center.x,
      latitude: center.y,
      spatialReference: mapView.spatialReference,
    });
    let textSymbol = new TextSymbol({
      //面积标注
      color: "white",
      haloColor: "black",
      haloSize: "2px",
      text: areaText,
      // xoffset: '50px',
      // yoffset: '-5px',
      font: {
        size: "16px",
        family: "sans-serif",
        weight: "bold",
      },
    });

    let textGraphics = new Graphic({
      //标注为面中心位置
      geometry: pointCenter,
      symbol: textSymbol,
    });
    polygonLayer.add(textGraphics);

    for (let i = 0; i < event.vertices.length; i++) {
      let point = {
        type: "point",
        x: event.vertices[i][0],
        y: event.vertices[i][1],
        spatialReference: mapView.spatialReference,
      };

      let pointGraphics = new Graphic({
        geometry: point,
        symbol: symbol,
      });
      polygonLayer.add(pointGraphics);
    }
    // polygonLayer.spatialReference = mapViewT.spatialReference;
    map.add(polygonLayer);
  }
}
//长度单位转换
function lengthFormat(length: number) {
  let lengthText = "";
  if (length < 2000) {
    // return lengthText = length + "meter"
    return (lengthText = length.toFixed(2) + "米");
  } else {
    let lengthN = (length / 1000).toFixed(2);
    // return lengthText = length + "kilometer"
    return (lengthText = lengthN + "千米");
  }
}

//面积单位转换
function areaFormat(area: number) {
  let areaText = "";
  // 平方米转亩数，使用乘法0.0015更准确  0.0015 = 1/666.666666667
  let areaN = (area * 0.0015).toFixed(2);
  return (areaText = areaN + "亩");
}
export {
  map,
  mapView,
  initMap,
  legendList,
  //地图工具
  operateFeatureLayer,
  //分屏显示
  dialogNormalVisible,
  selectType,
  screenChange,
  classType2,
  classType4,
  screenNum,
  cloNum,
  screenClass,
  screenSelectedLayer1,
  screenSelectedLayer2,
  screenSelectedLayer3,
  screenSelectedLayer4,
  operateFeatureLayerList,
  dialogRollerVisible, //卷帘
  rollerInit,
  leftSelectedLayer,
  rightSelectedLayer,
  allLayerList,
  leftChanged,
  rightChanged,
  dialogResultVisible,
};
